package com.example.distributedlockredisson.task;


import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ExcetorTask {

    @Autowired
    private RedissonClient redissonClient;
    private static final String LOCK_KEY = "task_lock";
    @Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次
    public void taskWithCronExpression() {
        RLock lock = redissonClient.getLock(LOCK_KEY);
        try {
            if (lock.tryLock()) {
              System.out.println("定时任务执行了"+System.currentTimeMillis());
            } else {
                log.info("另一台机器已经获得了锁，跳过执行定时任务");
            }
        } finally {
            lock.unlock();
        }
    }
}
